package spoon.support.builder;

import dk.au.cs.peterbn.spoonprocessing.Factory;
import org.eclipse.jdt.core.compiler.CategorizedProblem;

/**
* Created by IntelliJ IDEA.
* User: peter
* Date: 11/9/11
* Time: 11:42 AM
* To change this template use File | Settings | File Templates.
*/
public class MySpoonBuildingManager extends SpoonBuildingManager {

    private String cp;

    public MySpoonBuildingManager(Factory factory, String cp) {
        super(factory);
        this.cp = cp;
    }
    boolean build = false;

    @Override
    public boolean build() throws Exception {
        if (this.factory == null) {
            throw new Exception("Factory not initialized");
        }
        if (this.build) {
            throw new Exception("Model already built");
        }
        this.build = true;
        JDTCompiler.JAVA_COMPLIANCE = this.factory.getEnvironment()
                .getComplianceLevel();
        boolean srcSuccess, templateSuccess;
//        this.factory.getEnvironment().debugMessage(
//                "compiling sources: " + this.sources.getAllJavaFiles());
        long t = System.currentTimeMillis();
        this.compiler = new MyJDTCompiler(cp);
        this.initCompiler();
        srcSuccess = this.compiler.compileSrc(this.factory, this.sources.getAllJavaFiles());
        if (!srcSuccess) {
            for (CategorizedProblem[] cps : this.compiler.probs) {
                for (int i = 0; i < cps.length; i++) {
                    CategorizedProblem problem = cps[i];
                    if (problem != null)
                        this.getProblems().add(problem.getMessage());
                }
            }
        }
        this.factory.getEnvironment().debugMessage(
                "compiled in " + (System.currentTimeMillis() - t) + " ms");
        this.factory.getEnvironment().debugMessage(
                "compiling templates: " + this.templates.getAllJavaFiles());
        t = System.currentTimeMillis();
        templateSuccess = this.compiler.compileTemplate(this.factory, this.templates
                .getAllJavaFiles());
        this.factory.Template().parseTypes();
        this.factory.getEnvironment().debugMessage(
                "compiled in " + (System.currentTimeMillis() - t) + " ms");
        return srcSuccess && templateSuccess;
    }

}
